﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Web.Client.Services.Users;
using XCore.Web.Jwt;
using XCore.Logger;
using Web.Client.Model;
using XCore.Helper;
using XCore.Authorization;
using SaaS.Core;
using SaaS.Cache.Auths;
using SaaS.Model.Dto.Users;
using SaaS.Model.Enums;

namespace Web.Client.Controllers
{
    /// <summary>
    /// 账户中心
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : ClientControllerBase
    {
        private readonly UserAppService _userAppService;
        private readonly UserAuthCacheService _userCacheService;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="userAppService"></param>
        public AccountController(UserAppService userAppService, UserAuthCacheService userCacheService)
        {
            _userAppService = userAppService;
            _userCacheService = userCacheService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<JWTResult> Login(LoginInput input)
        {
            return _userAppService.Login(input.PhoneNumber, input.Password);
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<JWTResult> Register([FromBody]string username, [FromBody]string password, [FromBody]string code)
        {
            if (string.IsNullOrWhiteSpace(code)) throw new ClientException("验证码不能为空", ClientLoggerSource.LOGIN_REGISTER);
            return _userAppService.Registered(username, password);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, Permission]
        public ActionResult Info()
        {
            UserModel user = _userAppService.GetInfo(UserId.Value);
            return Ok(new
            {
                user.UserName,
            });
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Logout()
        {
            _userCacheService.RemoveUserToken(UserId.Value);
            return Ok("退出成功");
        }
    }
}